using UnityEngine;

namespace ZSW.Framework
{
    public class ZSWF_Singleton<T> : ZSWF_InitMonoBehaviour where T : MonoBehaviour
    {
        private static T instance;

        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = FindObjectOfType<T>();

                    if (instance == null)
                    {
                        GameObject singletonObject = new GameObject();

                        instance = singletonObject.AddComponent<T>();

                        singletonObject.name = $"[{typeof(T).Name}]";

                        DontDestroyOnLoad(singletonObject);
                    }
                }

                return instance;
            }
        }

        protected virtual void Awake()
        {
            if (instance == null)
            {
                instance = this as T;
            }
        }

        protected void OnApplicationQuit()
        {
            if (instance == this)
            {
                Destroy(this.gameObject);
            }
        }
    }
}